# _*_ coding:utf-8 _*_
# @Time :2021/4/21 18:21
# @Author :limeng
import copy
import datetime

from sqlalchemy import desc, func, or_

from application import db
from application.apps.collect.service import Sum_collect
from application.libs import sort_listdic, const, ymdhms_to_timestamp
from application.models.mantis_models import MantisProjectVersionTable, MantisBugTable
from application.models.models import CollectSum, Collect, Weekly, WeeklyCollectOperateLog


def get_weekly_time():
    """
    获取collect_sum表周时间
    :return:
    """
    data = db.session.query(CollectSum.updated_time).group_by(
        CollectSum.updated_time).order_by(desc(CollectSum.updated_time)).all()
    res = []
    if data:
        for i in data:
            j = i[0]
            j = j.strftime("%Y-%m-%d")
            if j not in res:
                res.append(j)
    return res


def get_weekly_bug_rate(parm):
    """
    获取近三周bug率
    :return:
    """
    bug_rate = {"legend_data": [], "legend_selected": {}, "xAxis_data": [], "series_data": {}}
    dic = {}

    if parm["last_week"] != '':
        last_week_project = []
        last_week_bug_rate = []
        dic_p_b = {}

        getBugRate(last_week_project, last_week_bug_rate, dic_p_b, parm["last_week"])
        dic["last_week"] = (last_week_project, last_week_bug_rate, dic_p_b)
        bug_rate["series_data"]["上周bug率"] = dic_p_b
        print("上周bug率",dic_p_b)
        if dic_p_b:
            bug_rate["legend_data"].append('上周bug率')
            bug_rate["legend_selected"]['上周bug率'] = True
    if parm["before_last_week"] != '':
        before_last_week_project = []
        before_last_week_bug_rate = []
        dic_p_b = {}
        # bug_rate["legend_data"].append('上上周bug率')
        # bug_rate["legend_selected"]['上上周bug率'] = True
        getBugRate(before_last_week_project, before_last_week_bug_rate, dic_p_b, parm["before_last_week"])
        dic["before_last_week"] = (before_last_week_project, before_last_week_bug_rate, dic_p_b)
        bug_rate["series_data"]["上上周bug率"] = dic_p_b
        if dic_p_b:
            bug_rate["legend_data"].append('上上周bug率')
            bug_rate["legend_selected"]['上上周bug率'] = True
    if parm["week"] != '':#如果周报手动选择第三周，则不进行计算当前之前一周的周报数据，同上即可
        this_week_project = []
        this_week_bug_rate = []
        dic_p_b = {}
        getBugRate(this_week_project, this_week_bug_rate, dic_p_b, parm["week"])
        dic["this_week"] = (this_week_project, this_week_bug_rate, dic_p_b)
        bug_rate["series_data"]["本周bug率"] = dic_p_b
        if dic_p_b:
            bug_rate["legend_data"].append('本周bug率')
            bug_rate["legend_selected"]['本周bug率'] = True
    else:
        if parm["this_week"] != '':
            this_week_project = []
            this_week_bug_rate = []
            dic_p_b = {}
            msg = Sum_collect.mainFun(0)
            if const.OPERATE_FAIL == msg:  # 避免脚本异常
                return {"legend_data": [], "legend_selected": {}, "xAxis_data": [], "series_data": {}}
            getBugRate(this_week_project, this_week_bug_rate, dic_p_b, parm["this_week"])
            dic["this_week"] = (this_week_project, this_week_bug_rate, dic_p_b)
            bug_rate["series_data"]["本周bug率"] = dic_p_b
            if dic_p_b:
                bug_rate["legend_data"].append('本周bug率')
                bug_rate["legend_selected"]['本周bug率'] = True
    if bug_rate["series_data"]:
        for i in bug_rate["series_data"].keys():
            if i == "上周bug率":
                v = bug_rate["series_data"][i].values()
                k = bug_rate["series_data"][i].keys()
                bug_rate["series_data"]["上周bug率"] = [round(float(i) * 100, 2) for i in list(v)]
                bug_rate["xAxis_data"] = list(k)
            if i == "上上周bug率":
                v = bug_rate["series_data"][i].values()
                k = bug_rate["series_data"][i].keys()
                bug_rate["series_data"]["上上周bug率"] = list(v)
                if bug_rate["xAxis_data"] and bug_rate["xAxis_data"] != list(k):
                    l = []
                    for j in bug_rate["xAxis_data"]:
                        l.append(dic["before_last_week"][2][j])
                    bug_rate["series_data"]["上上周bug率"] = [round(float(i) * 100, 2) for i in l]
            if i == "本周bug率":  # 本周的排序为准
                if bug_rate["series_data"]["本周bug率"]:
                    # bug_rate["legend_selected"]['本周bug率'] = True
                    # bug_rate["legend_data"].append('本周bug率')
                    d_bbr = sort_listdic(bug_rate["series_data"][i])
                    v = d_bbr.values()
                    k = d_bbr.keys()
                    bug_rate["series_data"]["本周bug率"] = [round(float(i) * 100, 2) for i in list(v)]
                    bug_rate["xAxis_data"] = list(k)
                    if bug_rate["series_data"].keys().__contains__("上上周bug率"):
                        l = []
                        for j in bug_rate["xAxis_data"]:
                            l.append(dic["before_last_week"][2][j])
                        bug_rate["series_data"]["上上周bug率"] = [round(float(i) * 100, 2) for i in l]
                    if bug_rate["series_data"].keys().__contains__("上周bug率"):
                        l = []
                        for j in bug_rate["xAxis_data"]:
                            if j in dic["before_last_week"][2].keys():
                                l.append(dic["last_week"][2][j])
                        bug_rate["series_data"]["上周bug率"] = [round(float(i) * 100, 2) for i in l]
                else:
                    bug_rate["legend_data"].append('本周bug率')
                    # bug_rate["legend_selected"]['本周bug率'] = True
                    bug_rate["series_data"]["本周bug率"] = []
    return bug_rate


def getBugRate(project_list, bug_rate_list, dic_p_b, week_time):
    """
    获取周bug率
    :param bug_rate_list:
    :param project_list:
    :param parm:
    :return:
    """
    last_week_start = datetime.datetime.strptime(week_time + " 00:00:00", "%Y-%m-%d %H:%M:%S")
    last_week_end = datetime.datetime.strptime(week_time + " 23:59:59", "%Y-%m-%d %H:%M:%S")
    if week_time != datetime.datetime.now().strftime('%Y-%m-%d'):
        data = db.session.query(CollectSum).filter(
            CollectSum.updated_time.between(last_week_start, last_week_end)).order_by(
            desc(CollectSum.updated_time)).all()
    else:
        data = db.session.query(CollectSum).filter(CollectSum.status == 1,
                                                   CollectSum.updated_time.between(last_week_start,
                                                                                   last_week_end)).order_by(
            desc(CollectSum.updated_time)).all()
    for i in data:
        if i in project_list:
            break
        project_list.append(i.business)
        bug_rate_list.append(i.bug_rate)
        dic_p_b[i.business] = i.bug_rate
    return {'project_list': project_list, 'bug_rate_list': bug_rate_list, 'dic_p_b': dic_p_b},


def get_weekly_collect(data):
    """
    获取相应时间内的项目指标收集列表
    :param data: 时间范围
    :return:list
    """
    collect_l = []
    parm = []
    if data["start_time"] and data["end_time"]:
        parm = [or_(Collect.onlinedate >= data['start_time'],
                    Collect.begindate >= data['start_time'],
                    Collect.enddate >= data['start_time']), or_(Collect.onlinedate <= data['end_time'],
                                                                Collect.begindate <= data['end_time'],
                                                                Collect.enddate <= data['end_time'])]
    parm.append(Collect.status != 0)
    c_data = db.session.query(Collect).filter(*parm).order_by(Collect.group).all()
    collect_ll = []  # 临时存储互动、资讯的collects
    if c_data:
        for i in c_data:
            if i.group == '互动' or i.group == '资讯':
                collect_ll.append({
                    "pid": i.pid,
                    "group": '内容·运营',
                    "project_version": i.group + " - " + i.project + " - " + i.version,
                    # "version": i.version,
                    "ptype": i.ptype,
                    "pstatus": i.pstatus,
                    "project_summary": "项目总结：\n" +
                                       "质量问题：",  # 项目总结
                    "mantis_address": mantis_address(i.project_id, i.version)
                })
            else:
                collect_l.append({
                    "pid": i.pid,
                    "group": i.group,
                    "project_version": i.project + " - " + i.version,
                    # "version": i.version,
                    "ptype": i.ptype,
                    "pstatus": i.pstatus,
                    "project_summary": "项目总结：\n" +
                                       "质量问题：",  # 项目总结
                    "mantis_address": mantis_address(i.project_id, i.version)
                })
    collect_ll.extend(collect_l)  # 集合合并,extend 方法会直接修改list数据， extend 方法的返回值为None
    return collect_ll


def mantis_address(project_id, version):
    ret = db.session.query(MantisProjectVersionTable).filter(MantisProjectVersionTable.project_id == project_id,
                                                             MantisProjectVersionTable.version == version).all()

    if ret:
        address = f"https://mantis.kcimg.cn/search.php?project_id={project_id}&sticky=on&" \
                  f"version={version}&sort=last_updated&dir=DESC&hide_status=-2&match_type=0"
    else:
        address = ""
    return address


def get_weekly_list(data):
    """
    周报列表查询
    :param data:
    :return:
    """
    parm = [Weekly.status == 1]
    # if data["start_time"] and data["end_time"]:
    #     parm.append(or_(Collect.onlinedate >= data['start_time'],
    #                     Collect.begindate >= data['start_time'],
    #                     Collect.enddate >= data['start_time'])),
    #     parm.append(or_(Collect.onlinedate <= data['end_time'], Collect.begindate <= data['end_time'],
    #                     Collect.enddate <= data['end_time']))
    page_data = db.session.query(Weekly).filter(*parm).order_by(Weekly.id.desc()).paginate(
        page=data[const.PAGE_NUM],
        per_page=data[const.PAGE_PER], error_out=False)
    response_list = []
    response_dic = {}
    if page_data.items:
        for weekly in page_data.items:
            response_dic['id'] = weekly.id
            response_dic['whole_bug_rate'] = str(round(float(weekly.whole_bug_rate) * 100, 4)) + "%"
            response_dic['whole_fixrate'] = str(round(float(weekly.whole_fixrate) * 100, 4)) + "%"
            response_dic['whole_unfixrate'] = str(round(float(weekly.whole_unfixrate) * 100, 4)) + "%"
            response_dic['whole_onlinerate'] = str(round(float(weekly.whole_onlinerate) * 100, 4)) + "%"
            response_dic['whole_bugcount'] = weekly.whole_bugcount
            response_dic['create_time'] = weekly.create_time
            response_dic['update_time'] = weekly.update_time.strftime("%Y-%m-%d %H:%M:%S")
            response_dic['last_operator'] = weekly.last_operator
            response_dic['create_date'] = weekly.create_date.strftime("%Y-%m-%d %H:%M:%S")
            response_dic['creater'] = weekly.creater
            response_dic['collects_count'] = len(eval(weekly.collects))
            response_list.append(response_dic.copy())
            response_dic.clear()
    response_dic['items'] = response_list
    response_dic['total'] = page_data.total
    return response_dic


def add_weekly(data):
    collect_p_data = db.session.query(func.sum(Collect.P1).label("P1"), func.sum(Collect.P2).label("P2"),
                                      func.sum(Collect.P3).label("P3"), func.sum(Collect.P4).label("P4"),
                                      func.sum(Collect.spendtime).label("spendtime"),
                                      func.sum(Collect.sumbugcount).label("sumbugcount"),
                                      func.sum(Collect.weibugcount).label("weibugcount"),
                                      func.sum(Collect.reopenbug).label("reopenbug"),
                                      func.sum(Collect.onlinecount).label("onlinecount"),
                                      func.sum(Collect.rollcount).label("rollcount")).all()

    if collect_p_data:
        collect_p_data = collect_p_data[0]
        bugrate = format((int(collect_p_data.P1) * 3 + int(collect_p_data.P2) * 2 + int(collect_p_data.P3) * 1 + int(
            collect_p_data.P4) * 0.5) / float(collect_p_data.spendtime),
                         '.2')
        fixrate = format(
            (int(collect_p_data.sumbugcount) - int(collect_p_data.weibugcount)) / int(collect_p_data.sumbugcount), '.2')
        unfixrate = format(int(collect_p_data.reopenbug) / int(collect_p_data.sumbugcount), '.2')
        onlinerate = format(
            (int(collect_p_data.onlinecount) - int(collect_p_data.rollcount)) / int(collect_p_data.onlinecount), '.2')
        bugcount = "0"
    else:
        bugrate, fixrate, unfixrate, onlinerate, bugcount = "--", "--", "--", "--", "0"
    oldCollects = None
    if data["id"]:  # 修改
        weekly_d = {
            "whole_bug_rate": bugrate,
            "whole_unfixrate": unfixrate,
            "whole_fixrate": fixrate,
            "whole_onlinerate": onlinerate,
            # "whole_bugcount": bugcount,
            "last_operator": data["creater"]
        }
        weekly = get_weekly(data["id"])
        if weekly:
            if data["collects"]:
                oldCollects = copy.deepcopy(weekly["collects"])
                for j in weekly["collects"]:
                    for i in data["collects"]:
                        if i["group"] == j["group"]:
                            j["project_summary"] = i["project_summary"]
                        # weekly["project_summary"] = data["collects"]["project_summary"]
                weekly_d["collects"] = str(weekly["collects"])
        else:
            return "未查询到此周报详情,刷新列表后"
        db.session.query(Weekly).filter(Weekly.id == data["id"]).update(weekly_d)
    else:
        bugs_parm = []
        if data['start_time'] != '':
            bugs_parm.append(MantisBugTable.date_submitted >= ymdhms_to_timestamp(data['start_time'] + ' 00:00:00'))
        if data['end_time'] != '':
            bugs_parm.append(MantisBugTable.date_submitted <= ymdhms_to_timestamp(data['end_time'] + ' 23:59:59'))
        bug_res = db.session.query(func.count(MantisBugTable.id).label("bug_count")).filter(*bugs_parm).all()
        if bug_res:
            bugcount = bug_res[0][0]
        weekly = Weekly()
        weekly.create_time = data["start_time"] + " 至 " + data["end_time"]
        weekly.bug_rate_chart = str(data["bug_rate_chart"])
        weekly.last_week_date = data["last_week_date"]
        weekly.before_last_week_date = data["before_last_week_date"]
        weekly.this_week_date = data["this_week_date"]
        weekly.collects = str(data["collects"])
        weekly.collect_start_time = data["start_time"]
        weekly.collect_end_time = data["end_time"]
        weekly.creater = data["creater"]
        weekly.whole_bug_rate = bugrate
        weekly.whole_fixrate = fixrate
        weekly.whole_unfixrate = unfixrate
        weekly.whole_onlinerate = onlinerate
        weekly.status = 1
        weekly.last_operator = data["creater"]
        weekly.create_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        weekly.whole_bugcount = bugcount
        db.session.add(weekly)
    try:
        db.session.commit()
        if data["id"]:  # 只有修改进行添加操作日志
            weeklyCollectOperateLog(data, oldCollects)
        return const.OPERATE_SUCCESS
    except:
        # 事務回滾
        db.session.rollback()
        return const.OPERATE_FAIL


def weeklyCollectOperateLog(data, oldCollects1):
    # 添加日志
    dic = {k["group"]: k["project_summary"] for k in data["collects"]}
    dic_old = {}
    if oldCollects1:
        dic_old = {h["group"]: h["project_summary"] for h in oldCollects1}
    objects = []
    create_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    for i in dic.keys():
        w_o_log = WeeklyCollectOperateLog()
        w_o_log.group = i
        if dic_old:
            w_o_log.collect_summary_old = dic_old[i]
        else:
            w_o_log.collect_summary_old = None
        w_o_log.collect_summary = dic[i]
        w_o_log.create_time = create_time
        w_o_log.weekly_id = data["id"]
        w_o_log.operator = data["creater"]
        objects.append(w_o_log)
    db.session.add_all(objects)
    try:
        db.session.commit()
    except:
        # 事務回滾
        db.session.rollback()


def get_weekly(id):
    """
    获取周报详情
    :param id:
    :return:
    """
    data = db.session.query(Weekly).filter(Weekly.id == id, Weekly.status == 1).first()
    weekly = {}
    if data:
        bug_rate_chart = data.bug_rate_chart
        weekly["bug_rate_chart"] = eval(bug_rate_chart)
        weekly["last_week_date"] = data.last_week_date
        weekly["before_last_week_date"] = data.before_last_week_date
        weekly["this_week_date"] = data.this_week_date
        weekly["collects"] = eval(data.collects)
        weekly["collect_start_time"] = data.collect_start_time
        weekly["collect_end_time"] = data.collect_end_time
    else:
        weekly = None
    return weekly


def delete_weekly(id):
    """
    周报 - -删除
    :param id:
    :return:
    """
    collect = db.session.query(Weekly).filter(Weekly.id == id, Weekly.status == 1).first()
    msg = const.DELETE_FAIL
    if collect:
        db.session.query(Weekly).filter(Weekly.id == id).update({"status": 0})
        try:
            db.session.commit()
            msg = const.DELETE_SUCCESS
        except:
            # 事務回滾
            db.session.rollback()
            msg = const.DELETE_FAIL
    return msg
